package com.example.myapplication.utils;

import android.util.Log;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;

public class WSHelper {
    private static WSHelper mInstance;
    private WebSocketClient client;
    private URI serverUri;
    private WSHelper() {
        try {
            serverUri = new URI("wss://echo.websocket.org/");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        client = new WebSocketClient(serverUri) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                Log.d("WebSocket", "WebSocket Opened");
            }

            @Override
            public void onMessage(String message) {
                Log.d("WebSocket", message);
            }

            @Override
            public void onMessage(ByteBuffer bytes) {
                super.onMessage(bytes);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                Log.d("WebSocket", "WebSocket Closeed");
            }

            @Override
            public void onError(Exception ex) {

            }
        };
    }

    public static WSHelper getInstance() {
        if(mInstance == null)
            mInstance = new WSHelper();
        return mInstance;
    }

    public void connect() {
        client.connect();
    }

    public void sendMessage(String msg) {
        client.send(msg);
    }
}
